<%@page import="com.google.api.client.googleapis.auth.oauth2.*,
        com.google.api.client.http.*,
        com.google.api.client.json.*,
        com.google.api.services.drive.*,
        com.google.api.services.drive.DriveScopes,
        com.google.api.client.json.jackson.*,
        com.google.api.services.drive.model.*,
        com.google.api.client.http.javanet.*,
        com.google.api.services.drive.Drive,
        com.google.api.services.drive.DriveScopes,
        com.google.api.services.drive.model.File,

        java.io.BufferedReader,
        java.io.IOException,
        java.io.InputStreamReader,
        java.util.*"
        %>


<%!    private static String CLIENT_ID = "488193432837.apps.googleusercontent.com";
    private static String CLIENT_SECRET = "aHnjIP9ZsxE9VGaQkApaIsLS";
    private static String REDIRECT_URI = "http://localhost:8084/gdrive";

    public static void main(String[] args) throws IOException {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
                .setAccessType("online")
                .setApprovalPrompt("auto").build();

        String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
        System.out.println("Please open the following URL in your browser then type the authorization code:");
        System.out.println("  " + url);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String code = br.readLine();

        GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

        //Create a new authorized API client
        Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

        //Insert a file  
        File body = new File();
        body.setTitle("My document");
        body.setDescription("A test document");
        body.setMimeType("text/plain");

        java.io.File fileContent = new java.io.File("document.txt");
        FileContent mediaContent = new FileContent("text/plain", fileContent);

        File file = service.files().insert(body, mediaContent).execute();
        System.out.println("File ID: " + file.getId());
    }

%>

<%
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
            .setAccessType("online")
            .setApprovalPrompt("auto").build();
    GoogleCredential credential;
    if (session.getAttribute("cred") == null && request.getParameter("code") == null) {
        String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
        out.println("Please open the following URL in your browser then type the authorization code:");
        out.println("  " + url);
        return;
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    } else {
        credential = (GoogleCredential) session.getAttribute("cred");
    }
    if (request.getParameter("code") != null) {
        String code = request.getParameter("code");

        GoogleTokenResponse gresponse = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
        credential = new GoogleCredential().setFromTokenResponse(gresponse);
        session.setAttribute("cred", credential);
    }
    //Create a new authorized API client

    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();
    Drive.Files df = service.files();
    //df.list().setMaxResults(new Integer(100000));
    List<File> dlf = df.list().setMaxResults(new Integer(1000))
            .setQ("mimeType = 'application/vnd.google-apps.folder'")
            .execute().getItems();
    //out.println("lf=" + lf.size());
    for (int i = 0; i < dlf.size(); i++) {
        try {
            if (service.children().list(dlf.get(i).getId())
                    .setQ("mimeType = 'application/vnd.google-apps.folder'").execute().getItems().size() == 0) {
                out.print(dlf.get(i).getTitle() + " " + dlf.get(i).getWebContentLink() + " <br/>");

                List<ChildReference> lf = service.children().list(dlf.get(i).getId())
                        .setQ("title contains '.pdf'").execute().getItems();
                for (int j = 0; j < lf.size(); j++) {
                    File pdfFile = service.files().get(lf.get(j).getId()).execute();
                    if ("PDF".equalsIgnoreCase(pdfFile.getFileExtension())) {

                        String fileName = pdfFile.getTitle();
                        String mylink = pdfFile.getWebContentLink();
                        String stateTime = null;
                        String grade = null;

                        List<ParentReference> pl = pdfFile.getParents();
                        for (ParentReference pr : pl) {
                            File file = df.get(pr.getId()).execute();
                            out.println(file.getTitle() + "...<br/>");
                            stateTime = file.getTitle();
                            file = df.get(file.getParents().get(0).getId()).execute();
                            out.println(file.getTitle() + "...<br/>");
                            grade = file.getTitle().split(" ")[1];
                        }
                        String url = "http://localhost/wordlist/exam_put.jsp?fileName=" + fileName + "&stateTime=" + stateTime
                                + "&grade=" + grade + "&mylink=" + mylink;
                        out.println(url + "<br/>");
                        java.net.URL myurl = new java.net.URL(url);
                        myurl.openStream().close();

                    }
                }
            }
        } catch (Exception e) {
            out.println(e);
        }
    }

%>
